//
//  LBActionSheet.m
//  app
//
//  Created by LINAICAI on 16/8/23.
//  Copyright © 2016年 广东联结电子商务有限公司. All rights reserved.
//

#import "LBActionSheet.h"
#import "LBImagePickerController.h"
#import <LBCategory/UIApplication+LBViewController.h>
@interface LBActionSheetDelegate : NSObject<UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic,strong) void(^block)(NSInteger);
@property (nonatomic,strong) void(^completion)(NSDictionary<NSString *,id> *);
+(void)addDelegate:(LBActionSheetDelegate*)delegate;
+(void)removeDelegate:(LBActionSheetDelegate*)delegate;
@end

@implementation LBActionSheet

/**
 *  工厂方法，原生控件block封装
 *
 *  @param title
 *  @param cancelButtonTitle      取消按钮
 *  @param destructiveButtonTitle 红色按钮
 *  @param otherButtonTitles      普通蓝色按钮
 *  @param complete               dismiss或者点击按钮的回调
 */
+ (void)showWithView:(__kindof UIView *)view
               block:(void(^)(NSInteger))block
               title:(NSString *)title
   cancelButtonTitle:(NSString *)cancelButtonTitle
destructiveButtonTitle:(NSString *)destructiveButtonTitle
   otherButtonTitles:(NSString *)otherButtonTitles, ...{
    LBActionSheetDelegate *delegate = nil;
    if (block) {
        delegate = [[LBActionSheetDelegate alloc] init];
        delegate.block = block;
        [LBActionSheetDelegate addDelegate:delegate];
    }
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:title delegate:delegate cancelButtonTitle:cancelButtonTitle destructiveButtonTitle:destructiveButtonTitle otherButtonTitles:nil];
    //参数链表指针
    va_list list;
    //遍历开始
    va_start(list, otherButtonTitles);
    //知道读取到下一个时nil时结束递增
    for (NSString *str = otherButtonTitles; str != nil; str = va_arg(list, NSString*)) {
        
        [sheet addButtonWithTitle:str];
    }
    //结束遍历
    va_end(list);
    [sheet showInView:view];
    
}
/**
 *  工厂方法，弹出图片选择ActionSheet
 *
 *  @param view       弹出视图
 *  @param info       选择的图片描述
 *  @param completion 回调
 */
+ (void)showImagePickerInView:(__kindof UIView *)view
                   completion:(void(^)(NSDictionary<NSString *,id> *))completion{
    LBActionSheetDelegate *delegate = nil;
    if (completion) {
        delegate = [[LBActionSheetDelegate alloc] init];
        delegate.completion = completion;
        [LBActionSheetDelegate addDelegate:delegate];
    }
    UIActionSheet *sheet;
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        sheet  = [[UIActionSheet alloc] initWithTitle:@"选择" delegate:delegate cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册选择", nil];
    } else {
        sheet = [[UIActionSheet alloc] initWithTitle:@"选择" delegate:delegate cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从相册选择", nil];
    }
    [sheet showInView:view];
}

+ (UIImage *)fixOrientation:(UIImage *)aImage {
    
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}


@end
@implementation LBActionSheetDelegate

static __strong NSMutableArray *__delegates;
+(NSMutableArray*)delegates{
    static dispatch_once_t pred = 0;
    dispatch_once(&pred, ^{
        __delegates = [[NSMutableArray alloc] init];
    });
    return __delegates;
}
+(void)addDelegate:(LBActionSheetDelegate*)delegate{
    [[self delegates] addObject:delegate];
}
+(void)removeDelegate:(LBActionSheetDelegate*)delegate{
    [[self delegates] removeObject:delegate];
}
#pragma mark- UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet willDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (self.block) {
        self.block(buttonIndex);
        [[self class] removeDelegate:self];
    }
    
}

- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex{
    NSUInteger sourceType = 2;
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        switch (buttonIndex) {
            case 0:
                // 相机
                sourceType = UIImagePickerControllerSourceTypeCamera;
                break;
            case 1:
                // 相册
                sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                break;
            case 2:
                return;
        }
    } else {
        if (buttonIndex == 0) {
            sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        } else {
            return;
        }
    }
    
    LBImagePickerController *imagePickerController =  [[LBImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = sourceType;
    [[UIApplication getCurrentViewController] presentViewController:imagePickerController animated:YES completion:nil];
}
#pragma mark- UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    __weak typeof(self) weakSelf = self;
    [picker dismissViewControllerAnimated:YES completion:^{
        if (weakSelf.completion) {
            weakSelf.completion(info);
            [[weakSelf class] removeDelegate:weakSelf];
        }
        
    }];
}
@end
